package io.afu.baseframework.annotations.impls;

import com.alibaba.fastjson.JSON;
import io.afu.baseframework.annotations.Permission;
import io.afu.baseframework.service.PermissionService;
import io.afu.common.constant.ConstantEnum;
import io.afu.common.dto.BaseRespDto;
import io.afu.common.exception.BaseException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

/**
 * @author RffanLAB.方露宇
 * @version 0.1
 */
@Aspect
@Component
public class PermissionImpl {

    private Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    PermissionService permissionService;


    @Pointcut(value = "@annotation(io.afu.baseframework.annotations.Permission)")
    public void cutPermission(){

    }

    @Around("cutPermission()")
    public Object CheckPermission(ProceedingJoinPoint point) throws Throwable {
        //先执行业务
        Object result = point.proceed();
        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();

        Permission permission = method.getAnnotation(Permission.class);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            throw new BaseException(ConstantEnum.API_HAS_NO_PERMISSION);
        }
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        // 执行鉴权
        permissionService.checkPermission(request,response,permission);
        // 返回执行结果- -
        return result;
    }




    private void flushOut(HttpServletResponse response, BaseException e) throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.setContentType("application/json");
        String result = JSON.toJSONString(BaseRespDto.fail(e));
        logger.info("数据为："+result);
        OutputStream os = response.getOutputStream();
        os.write(result.getBytes(StandardCharsets.UTF_8.toString()));
        os.flush();
    }




}
